package com.wasp.java.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;

public class TXTFileUtil{
	public static void create(File file) throws IOException {
		if (!file.exists()) {
			file.createNewFile();
		}
	}
	
	/**
	 * 
	 * @return
	 * @throws Exception 
	 * FileNotFoundException/IOException
	 */
	public static String read(File file) throws Exception {
		String readStr = "";
		if (file.isDirectory()) {
		} else {
			BufferedReader bufread;
			FileReader fileread;
			fileread = new FileReader(file);
			bufread = new BufferedReader(fileread);
			String read;
			while ((read = bufread.readLine()) != null) {
				readStr = readStr + read + "\r\n";
			}
		}
		return readStr;
	}
	
	/**
	 * write the content to the file
	 * @param newStr
	 * @throws IOException
	 */
	public static void write(File file,String newStr) throws IOException {
		if(file.isDirectory())
		{}else{
			String filein = newStr + "\r\n";
			RandomAccessFile mm = null;
			try {
				mm = new RandomAccessFile(file, "rw");
				mm.writeBytes(filein);
			} catch (IOException e1) {
				e1.printStackTrace();
			} finally {
				if (mm != null) {
					try {
						mm.close();
					} catch (IOException e2) {
						e2.printStackTrace();
					}
				}
			}
		}
	}
	
	/**
	 * append text to the file.
	 * @param newStr
	 * @throws IOException
	 */
	public static void append(File file,String newStr) throws IOException {
		String filein = newStr + "\r\n";
		try {
			StringBuffer buf = new StringBuffer();
			buf.append(filein);
			FileOutputStream fos = new FileOutputStream(file,true);
			PrintWriter pw = new PrintWriter(fos);
			pw.write(buf.toString().toCharArray());
			pw.flush();
			pw.close();
		} catch (IOException e1) {
			// TODO 自动生成 catch 块
			e1.printStackTrace();
		} finally {
		}
	}

}
